//
//  ViewController.m
//  ppkc2016
//
//  Created by 拼凑的断音 on 16/3/2.
//  Copyright © 2016年 拼凑的断音. All rights reserved.
//

#import "ViewController.h"
#import "XXTool.h"
#import "SelectRegistrationStatusViewController.h"
#import "PresentProjectMainCotroller.h"
#import "PersonInfoViewController.h"

#import "XMLMapListModel.h"

@interface ViewController ()<UIAlertViewDelegate>

@end

@implementation ViewController
{
    NSString *skip;
    
    NSMutableArray <XMLMapListModel *> *needUpdateMapArray;
    BOOL hallUpdate;
    BOOL paroUpdate;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    [UserInfo shareUserInfo].userID = [user objectForKey:userIDString];
    [UserInfo shareUserInfo].userPassword = [user objectForKey:userPassword];
    [UserInfo shareUserInfo].userName = [user objectForKey:userName];
    [UserInfo shareUserInfo].userCompany = [user objectForKey:userCompany];
    [UserInfo shareUserInfo].userHeadImgUrl = [user objectForKey:userHeadImgUrl];
    [UserInfo shareUserInfo].isExhibitor = [user boolForKey:userIsExhibitor];
    if ([UserInfo shareUserInfo].userID==nil)
    {
        [UserInfo shareUserInfo].userID = @"";
    }
    if ([UserInfo shareUserInfo].userName==nil)
    {
        [UserInfo shareUserInfo].userName = @"";
    }
    
    UIImageView *img = [[UIImageView alloc] init];
    img.frame = [UIScreen mainScreen].bounds;
    img.image = [UIImage imageNamed:@"launchBG.jpg"];
    
    img.contentMode = UIViewContentModeScaleAspectFill;
    img.clipsToBounds = YES;
    img.alpha = 0.2;
    [self.view addSubview:img];
    
    UIImageView *logo = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"launchlogo"]];
    logo.frame = CGRectMake(([UIScreen mainScreen].bounds.size.width-[UIScreen mainScreen].bounds.size.width*560/750)/2
                            , [UIScreen mainScreen].bounds.size.height*290/1334
                            , [UIScreen mainScreen].bounds.size.width*560/750
                            , [UIScreen mainScreen].bounds.size.width/750*138);
    logo.contentMode = UIViewContentModeScaleAspectFit;
    [img addSubview:logo];
    
    UIImageView *center = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"launchCenter"]];
    center.frame = CGRectMake(([UIScreen mainScreen].bounds.size.width-[UIScreen mainScreen].bounds.size.width*34/750)/2
                              , [UIScreen mainScreen].bounds.size.height*577/1334
                              , [UIScreen mainScreen].bounds.size.width*34/750
                              , [UIScreen mainScreen].bounds.size.width/750*26);
    center.contentMode = UIViewContentModeScaleAspectFit;
    [img addSubview:center];
    
    UIImageView *text = [[UIImageView alloc]init];
    text.contentMode = UIViewContentModeScaleAspectFit;
    if([XXTool didCurrentLanguageChinese])
    {
        text.image = [UIImage imageNamed:@"launchC"];
        text.frame = CGRectMake(([UIScreen mainScreen].bounds.size.width-[UIScreen mainScreen].bounds.size.width*320/750)/2, [UIScreen mainScreen].bounds.size.height*675/1334
                                , [UIScreen mainScreen].bounds.size.width*320/750
                                , [UIScreen mainScreen].bounds.size.width/750*89);
    }
    else
    {
        text.image = [UIImage imageNamed:@"launchE"];
        text.frame = CGRectMake(([UIScreen mainScreen].bounds.size.width-[UIScreen mainScreen].bounds.size.width*610/750)/2, [UIScreen mainScreen].bounds.size.height*675/1334
                                , [UIScreen mainScreen].bounds.size.width*610/750
                                , [UIScreen mainScreen].bounds.size.width/750*88);
    }
    [img addSubview:text];
    
    [UIView animateWithDuration:4.0
                     animations:^{
                         img.alpha = 1;
                         
                     } completion:^(BOOL finished) {
                         if (![[UserInfo shareUserInfo].userID isEqualToString:@""]) //已经登录
                         {
                             if ([UserInfo shareUserInfo].isExhibitor&&[[UserInfo shareUserInfo].userName isEqualToString:@""]) //展商同时没有填写用户资料
                             {
                                 [PersonInfoViewController presentPersonInfoVCWithSourceVC:self personInfoViewControllerType:PersonInfoViewControllerDidExhibitorPerfect];
                             }
                             else
                             {
                                 [PresentProjectMainCotroller getProjectMainControllerWithSoureViewController:self showTipType:PresentProjectMainCotrollerSkip];
//                                 [[NSNotificationCenter defaultCenter] postNotificationName:@"successLogin" object:nil];
                             }
                         }
                         else //没有登录过，先加载主页面在present出登陆页面
                         {
                             [PresentProjectMainCotroller getProjectMainControllerWithSoureViewController:self showTipType:PresentProjectMainCotrollerNeedLogin];
                             [[NSNotificationCenter defaultCenter] postNotificationName:@"successLoginAndFirstIntro" object:nil];
                         }
                     }];
    [self checkVision];
    [self checkMap];
}

-(void)checkVision
{
    int visionEX = 1;  //强制更新版本号
    int vision = 20170811;   //正常更新版本号

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"提示", nil) message:NSLocalizedString(@"发现一个新版本,请更新", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"取消", nil) otherButtonTitles:NSLocalizedString(@"更新",nil), nil];
    [DKHTTPRequest sendDataWithShortUrl:@"index_version"
                                  Param:[XXTool formatStringWithLanguage:@""]
                             ImageArray:nil
                                TimeOut:10
                             Completion:^BOOL(NSMutableDictionary *serverDic, DKHTTPResponseType bufferType) {
                                 if ([[serverDic objectForKey:@"code"] intValue]==200)
                                 {
                                     
                                     if (visionEX<[[serverDic objectForKey:@"ios_version_ex"] intValue])
                                     {
                                         skip = [serverDic objectForKey:@"ios_url"];
                                         alert.tag = 1;
                                         [alert show];
                                     }
                                     else if (vision<[[serverDic objectForKey:@"ios_version"] intValue])
                                     {
                                         skip = [serverDic objectForKey:@"ios_url"];
                                         alert.tag = 2;
                                         [alert show];
                                     }
                                 }
                                 return YES;
                             } IsBuffering:NO
                      IsNeedReplaceWrap:NO
                        IsUseUpLoadHead:NO];
}

-(void)checkMap
{
    __block int mark = 0;
    hallUpdate = NO;
    paroUpdate = NO;

    needUpdateMapArray = [NSMutableArray array];
    [XMLMapListModel checkMapWithMtype:1 complete:^(BOOL isNeedUpdate, NSMutableArray<XMLMapListModel *> *updateMapArray) {
        if (isNeedUpdate)
        {
            hallUpdate = YES;
            [needUpdateMapArray addObjectsFromArray:updateMapArray];
        }
        mark ++;
        if (mark == 2)
        {
            [self isNeedShowAlert];
        }
    }];
    
    [XMLMapListModel checkMapWithMtype:2 complete:^(BOOL isNeedUpdate, NSMutableArray<XMLMapListModel *> *updateMapArray) {
        if (isNeedUpdate)
        {
            paroUpdate = YES;
            [needUpdateMapArray addObjectsFromArray:updateMapArray];
        }
        mark ++;
        if (mark == 2)
        {
            [self isNeedShowAlert];
        }
    }];
}

-(void)isNeedShowAlert
{
    if (paroUpdate||hallUpdate)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"提示", nil)
                                                        message:NSLocalizedString(@"有新地图，是否更新", nil)
                                                       delegate:self
                                              cancelButtonTitle:NSLocalizedString(@"取消", nil)
                                              otherButtonTitles:NSLocalizedString(@"确定", nil), nil];
        alert.tag = 3;
        [alert show];
    }
}

#pragma mark alertviewDelegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (alertView.tag)
    {
        case 1:  //强制更新
        {
            if (buttonIndex==1)
            {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:skip]];
            }
            exit(0);
        }
            break;
            
        case 2:  //正常更新
        {
            if (buttonIndex==1)
            {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:skip]];
            }
        }
            break;
        case 3: //地图更新
        {
            if (buttonIndex==1)
            {
                NSMutableArray <XMLXXDownFileModel*>* downfileArray = [NSMutableArray array];
                
                if (needUpdateMapArray.count > 0)
                {
                    for (int i = 0; i < needUpdateMapArray.count; i ++)
                    {
                        XMLMapListModel *temp = needUpdateMapArray[i];
                        XMLXXDownFileModel *img = [XMLXXDownFileModel newXXDownFileModelWithUrl:temp.mappath saveName:[NSString stringWithFormat:@"%@%@.png",temp.mtype,temp.mapname] saveType:IMG];
                        [downfileArray addObject:img];
                        
                        if ([temp.mtype integerValue] == 1)
                        {
                            XMLXXDownFileModel *html = [XMLXXDownFileModel newXXDownFileModelWithUrl:temp.mapphtml saveName:[NSString stringWithFormat:@"%@%@.html",temp.mtype,temp.mapname] saveType:HTML];
                            [downfileArray addObject:html];
                        }
                    }
                }

                UIAlertView *progressAlert = [[UIAlertView alloc] initWithTitle:nil
                                                                        message:NSLocalizedString(@"正在下载", nil)
                                                                       delegate:self
                                                              cancelButtonTitle:NSLocalizedString(@"取消", nil)
                                                              otherButtonTitles:nil, nil];
                [progressAlert showWithProgress];
                [progressAlert show];
                
                [XXDownFileToFoler
                 downFileWithUrlArray:downfileArray
                  downProgressBlock:^(float rate) {
                      [progressAlert setProgressWithRate:rate];
                  } completeBlock:^(BOOL isSuccess) {
                      [progressAlert dismissWithClickedButtonIndex:0 animated:NO];
                      [SVProgressHUD showSuccessWithStatus:NSLocalizedString(@"地图更新成功", nil)];
                      //地图更新成功，更新地图对应版本号
                      NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
                      for (int i = 0; i < needUpdateMapArray.count; i ++)
                      {
                          XMLMapListModel *temp = needUpdateMapArray[i];
                          [user setInteger:[temp.mapversion integerValue] forKey:[NSString stringWithFormat:@"%@%@%@",temp.mtype,mtypeMapVision,temp.mapname]];
                      }
                      [user synchronize];
                  }];
            }
        }
            break;
        default:
            break;
    }
}

@end
